package com.dataeco.api.service.impl;

import com.dataeco.api.entity.User;
import com.dataeco.api.facility.PasswordService;
import com.dataeco.api.facility.Snowflake;
import com.dataeco.api.repository.UserRepository;
import com.dataeco.api.service.UserService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl implements UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserRepository userRepository;
    private final PasswordService passwordService;
    private final Snowflake snowflake;

    public UserServiceImpl(UserRepository userRepository, PasswordService passwordService, Snowflake snowflake) {
        this.userRepository = userRepository;
        this.passwordService = passwordService;
        this.snowflake=snowflake;
    }

    @Override
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    @Override
    public User authenticate(String loginName, String loginPass) {
        User user = userRepository.findByEmail(loginName);
        if (user == null) {
            throw new UnknownAccountException();
        }
        String salt = user.getSalt();
        String credentials = user.getCredentials();
        String encryptPassword = passwordService.encryptPassword(loginPass, salt);
        LOGGER.debug("loginPass={}, salt={}, encryptedPassword={}, credentials={}", loginName, salt, encryptPassword, credentials);
        if (!encryptPassword.equals(credentials)) {
            throw new IncorrectCredentialsException();
        }
        return user;
    }

    @Override
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public User findOne() {
        User user=userRepository.findOne(getUserId());
        if (Objects.isNull(user)){
            return null;
        }
        return user;
    }

    @Override
    public User saveUserWhenSignup(User user) {
        return userRepository.save(user);
    }

}
